package com.leaf.lowcode.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.leaf.lowcode.API.DoorFunctionApi;
import com.leaf.lowcode.entity.Dooreven;
import com.leaf.lowcode.entity.DoorevenDTO;
import com.leaf.lowcode.entity.door_control.EventsRequest;
import com.leaf.lowcode.mapper.DoorevenMapper;
import com.leaf.lowcode.utils.RegularInstance;
import com.leaf.lowcode.utils.jsontobean.JsonToBeanV;
import com.tencent.welink.iot.SubDeviceDTO;
import com.tencent.welink.iot.WelinkHttp;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;


/**
 * 门禁员工通行率
 */

@Component
public class DoorEvetime {

    @Autowired
    private DoorevenMapper doorevenMapper;
    @Scheduled(initialDelay = 6* 1000, fixedRate = 60* 1000)
    public void execute() {
        List<SubDeviceDTO> subDeviceDTOList = RegularInstance.subDeviceDTOList;
        System.out.println("subDeviceDTOList"+subDeviceDTOList);
          /*  String pattern = "YYYY-MM-dd'T'HH:mm:ssZZ";
        String data=DateFormatUtils.format(new Date(),pattern);*/

        Calendar calendar = new GregorianCalendar();
        calendar.add(Calendar.DAY_OF_MONTH,0);
        //一天的开始时间 yyyy:MM:dd 00:00:00
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        Date dayStart = calendar.getTime();
        String pattern = "YYYY-MM-dd'T'HH:mm:ssZZ";
        String startStr =DateFormatUtils.format(dayStart,pattern);
        System.out.println("startStr"+startStr);
        //一天的结束时间 yyyy:MM:dd 00:00:00
        calendar.set(Calendar.HOUR_OF_DAY,23);
        calendar.set(Calendar.MINUTE,59);
        calendar.set(Calendar.SECOND,59);
        calendar.set(Calendar.MILLISECOND,999);
        Date dayEnd = calendar.getTime();
        String endStr=DateFormatUtils.format(dayEnd,pattern);
        System.out.println("startStr"+endStr);

        DoorFunctionApi doorFunctionApi=  new DoorFunctionApi();
        EventsRequest eventsRequest=new EventsRequest();
        eventsRequest.setPageNo(1);
        eventsRequest.setPageSize(1000);
        eventsRequest.setStartTime(startStr);
        eventsRequest.setEndTime(endStr);
        String doorcount=doorFunctionApi.events(eventsRequest);
        JSONObject jsonObject = JSONObject.parseObject(doorcount);
        JSONArray list = (JSONArray) ((JSONObject) jsonObject.get("data")).get("list");
        System.out.println(list);
        Dooreven dooreven =new Dooreven();
        DoorevenDTO doorevenDTO= new DoorevenDTO();
        for(int i=0;i<list.size();i++) {
            JSONObject object = (JSONObject) list.get(i);
            JsonToBeanV<Dooreven> jsonToBeanV = new JsonToBeanV<Dooreven>();
            dooreven = jsonToBeanV.tansfrom(dooreven, object);
            BeanUtils.copyProperties(dooreven, doorevenDTO);
            if (doorevenDTO.getInAndOutType().equals("0") || doorevenDTO.getOrgName().equals("0"))
                continue;
            if (doorevenDTO.getDoorName().contains("1F")==true) {
              doorevenDTO.setOrgName(doorevenDTO.getOrgName().replaceFirst("默认组织/",""));
                DoorevenDTO flog = doorevenMapper.selectId(doorevenDTO.getEventId(),doorevenDTO.getCertNo());
                if (flog == null) {
                   System.out.println("不存在");
                    doorevenMapper.insert(doorevenDTO);
                    if (subDeviceDTOList != null) {
                        for (SubDeviceDTO dto : subDeviceDTOList) {
                            String pid = dto.getPid();
                            String sn = dto.getSn();
                     //       System.out.println("sn"+sn);
                            String din = dto.getDin();
                            if (doorevenDTO.getDoorIndexCode().equals(sn)) {
                                System.out.println("门禁事件");
                                //  System.out.println("======================门禁卡========================"+readerdoorstatesend.getIndexCode());
                                JSONObject standardData = new JSONObject();
                                standardData.put("reportTs", System.currentTimeMillis());
                                JSONObject profile = new JSONObject();
                                profile.put("modelId", 200684);
                                profile.put("poiCode", "w0703000");
                                profile.put("appType","access_control");
                                standardData.put("profile", profile);
                                WelinkHttp wh = new WelinkHttp(RegularInstance.registerData1, RegularInstance.loginData);
                                JSONObject events = new JSONObject();
                                JSONObject event = new JSONObject();
                                event.put("eventType", 1);
                                event.put("eventTs", System.currentTimeMillis());
                                event.put("describe", "");
//                                doorevenInanOut.put("DoorIndexCode", doorevenDTO.getDoorIndexCode());
//                                doorevenInanOut.put("OrgName", doorevenDTO.getOrgName());
//                                doorevenInanOut.put("PersonName", doorevenDTO.getPersonName());
                               Class cls =doorevenDTO.getClass();
                                Field[] fields = cls.getDeclaredFields();
                                for (int k=0;k<fields.length;k++){//遍历
                                    try {
                                        //得到属性
                                        Field field = fields[k];
                                        //打开私有访问
                                        field.setAccessible(true);
                                        //获取属性
                                        String name = field.getName();
                                        //获取属性值
                                        Object value = field.get(doorevenDTO);
                                        //一个个赋值
                                        event.put(name,value);
                                    } catch (IllegalAccessException e) {
                                        e.printStackTrace();
                                    }
                                }
                                System.out.println("even"+event);
                                events.put("out", event);
                                standardData.put("events", events);
                                standardData.put("properties", new JSONObject());
                                //standardData.put("properties", "{}");
                                try {
                                      System.out.println("上传数据");
                                    String devRunEvent = JSONObject.toJSONString(standardData, SerializerFeature.WriteMapNullValue);
                                      System.out.println("发送设备运行时事件数据==" + devRunEvent);
                                        System.out.println("--------------------------------开始传输设备运行时事件数据");
                                    wh.sendMessage(RegularInstance.loginData.load(), 80000, Long.parseLong(din), devRunEvent, true);
                                } catch (Exception e) {
                                    System.out.println("设备运行时事件数据传输出现异常");
                                }
                            }
                        }
                    }

                } else {
               //     System.out.println("存在");
                }
            }
        }

      //  System.out.println(data);

    }
}
